<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Compose</title>
</head>

<body>


    <script>
        function clickEvent() {
            if (document.getElementById('media').value != "") {
                var formData = new FormData(document.getElementById('media-form'));
                const Http = new XMLHttpRequest();
                const url = 'http://' + window.location.hostname + ':8081/upload-media';
                Http.onreadystatechange = function () {
                    if (this.readyState == 4 && this.status == 200) {
                        var resp = JSON.parse(Http.responseText);
                        uploadPost(resp);
                    }
                };

                Http.open("POST", url, true);
                Http.send(formData);
            } else {
                uploadPost()
            }

        }

        function uploadPost(media_json) {
            if (document.getElementById('post_text').value !== "") {
                const Http = new XMLHttpRequest();
                const url = 'http://' + window.location.hostname + ':8080/api/post/compose';
                Http.open("POST", url, true);
                var body = "post_type=0&text=" + document.getElementById('post_text').value
                Http.onreadystatechange = function () {
                    if (this.readyState == 4 && this.status == 200) {
                        console.log(Http.responseText);
                    }
                };
                if (media_json === undefined) {
                    Http.send(body);
                } else {
                    body += "&media_ids=[\"" + media_json.media_id + "\"]&media_types=[\"" + media_json.media_type + "\"]"
                    Http.send(body);
                }
            }


        }
    </script>

    <form id="media-form" method="post" enctype="multipart/form-data">
        <input type="file" id="media" name="media" accept="image/*">
        <div></div>
    </form>


    <input type="text" id="post_text" name="text">
    <div></div>
    <input type="button" value="submit" onClick="clickEvent();">
    <div></div>



</body>

</html>